import wallet from '@caomei/wallet/lib/wxApp';
import createOrder from './apis/createOrder';

Page({
  data: {
    payInfo: null,
    paying: false,
  },
  async pay() {
    try {
      if (this.data.paying) {
        throw new Error('正在支付中');
      }
      this.setData({
        paying: true,
      });
      // 提交订单，并且获取支付串
      const { data: payInfo, code, message } = await createOrder(
        1001, // productType
        '5bfaa33d68194d39b9f81aea88b6808b', // itemId
        1, // num
      );

      // 请求错误
      if (code !== 1) {
        throw new Error(message);
      }

      this.setData({
        payInfo,
        paying: false,
      });

      // 唤起支付
      const res = await wallet.wxpay.payIt(payInfo);

      console.log('支付完成', res);
    } catch (err) {
      this.setData({
        paying: false,
      });
      console.error(err);
      wx.showModal({
        title: err.name,
        content: err.message,
        showCancel: false,
      });

      if (err.name === 'PayError') {
        if (err.resultCode === wallet.wxpay.CANCEL) {
          console.log('取消了支付');
        } else {
          console.log('支付失败');
        }
      }
    }
  },
});
